/**
 * 
 */
package com.edoomath.api.web.controller.user;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.edoomath.api.handler.QiniuHandler;
import com.edoomath.api.servcice.CourseItemService;
import com.edoomath.api.servcice.UserCourseService;
import com.edoomath.api.servcice.UserService;
import com.edoomath.api.servcice.WechatGroupService;
import com.edoomath.entity.course.CourseItem;
import com.edoomath.entity.course.wechatgroup.WechatGroup;
import com.edoomath.entity.user.User;
import com.edoomath.entity.usercourse.UserCourse;

/**
 * @author downpour
 *        
 */
@Controller
@RequestMapping("/wechat-groups")
public class WechatGroupController {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatGroupController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private WechatGroupService wechatGroupService;
    
    @Autowired
    private CourseItemService courseItemService;
    
    @Autowired
    private UserCourseService userCourseService;
    
    @Autowired
    private QiniuHandler qiniuHandler;
    
    /**
     * 
     * @param gid
     * @param opengid
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/{gid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult load(@PathVariable(value = "gid") Long gid,
                           @RequestParam(value = "opengid") String opengid,
                           @RequestParam("courseId") Long courseId) {
        
        HttpResult httpResult = new HttpResult();
        
        logger.info("start load wechatGroup with opengid[{}], gid[{}], courseid [{}]", opengid, gid, courseId);
        
        WechatGroup wechatGroup = wechatGroupService.loadWechatGroup(opengid, courseId);
        
        if(wechatGroup == null) {
            throw BusinessException.newInstance("500", "微信群暂未绑定");
        } else {
            if(wechatGroup.getId() != gid) {
                throw BusinessException.newInstance("400", "请求参数不匹配");    
            }
        }
        
        List<CourseItem> courseItems = courseItemService.listCourseItem(wechatGroup.getCourse());
        
        return httpResult.success()
                         .data("wechatGroup", wechatGroup)
                         .data("course", wechatGroup.getCourse())
                         .data("courseItems", courseItems);
    }
    
    /**
     * 
     * @param opengid
     * @return
     */
    @RequestMapping(value = "/opengid-load/{opengid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult loadByOpengid(@PathVariable(value = "opengid") String opengid,
                                    @RequestParam(value = "unionid", required = false) String unionid) {
        
        HttpResult httpResult = new HttpResult(); 
        
        logger.info("start load wechatGroup with opengid[{}]", opengid);
        
        try {
            WechatGroup wechatGroup = wechatGroupService.loadWechatGroup(opengid);
            
            if(StringUtils.isNotBlank(unionid)) {
                
                User user = userService.load(unionid);
                httpResult.data("user", user);
                
                UserCourse userCourse = userCourseService.loadUserCourse(unionid, wechatGroup.getCourse().getId());
                if(userCourse == null) {
                    httpResult.data("needBindcourse", true);
                }else {
                    httpResult.data("needBindcourse", false);
                }
            }
            
            return httpResult.success()
                             .data("wechatGroup", wechatGroup)
                             .data("course", wechatGroup.getCourse())
                             .message("获取成功");
            
        } catch (Exception e) {
            logger.error("occur", e);
            return httpResult.fail("500").message("获取群信息失败");
        }
    }
    
    /**
     * 
     * @param opengid
     * @return
     */
    @RequestMapping(value = "/opengid-validate-bind-mobile/{opengid}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult validateBindMobile(@PathVariable(value = "opengid") String opengid) {
        
        HttpResult httpResult = new HttpResult(); 
        
        logger.info("start validateBindMobile with opengid[{}]", opengid);
        
        boolean needValidate = true;
        
        if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5eYkrFB9MULA9cXKR3LAqdI")) {
            needValidate = false;
        } else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5VtSyqWbS-kxp9netAUHnVM")) {
            needValidate = false;
        } else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5ff7RnVtyNaE7fJyODFCLWk")) {
            needValidate = false;
        } else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5czGdQtqTjfcLvUwz-RxpVs")) {
            needValidate = false;
        }else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5fLJJ12dqF5cjksjF0NW4aQ")) {
            needValidate = false;
        }else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5a4yP9CzUtSBvlprmPDjG9k")) {
            needValidate = false;
        }else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5VMzHaeUEUNGHCXuTQAAlHo")) {
            needValidate = false;
        }else if(StringUtils.equalsIgnoreCase(opengid, "GPmgf5R_AtIE-usGm1lFyKFpt2_U")) {
            needValidate = false;
        }
        logger.info("start validateBindMobile with needValidate[{}]", needValidate);
//        else if(StringUtils.equalsIgnoreCase(opengid, "tGPmgf5VLiiH_6yUX17xYzbGMq_Cg")) {
//            needValidate = false;
//        }
        
        return httpResult.success()
                         .data("needValidate", needValidate);
    }

    /**
     * 
     * @param gid
     * @param opengid
     * @return
     */
    @RequestMapping(value = "/bind-group-url", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult generateBindUrl(@RequestParam(value = "url") String url) {
        
        HttpResult httpResult = new HttpResult();
        
        logger.info("start bind wechatGroup with url[{}]", url);
        
         String qrcode = qiniuHandler.generateQrCode(url);
         
         return httpResult.success().data("qrcode", qrcode);
    }
    
    /**
     * 
     * @param opengid
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/{opengid}/bind-usercourse", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult bindUserCourse(@PathVariable(value = "opengid") String opengid,
                                     @RequestParam("unionid") String unionid) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
        
            logger.info("start bind user course with opengid [{}], unionid [{}]", opengid, unionid);
            
            User user = userService.load(unionid);
            if(user.isChildren() && StringUtils.isNotBlank(user.getMobile())) {
                user = userService.getParent(user);
            }
            
            WechatGroup wechatGroup = wechatGroupService.loadWechatGroup(opengid);
            
            if(StringUtils.isBlank(wechatGroup.getOpengid())) {
                logger.error("bind user course faild with message : [{}]", "群暂未绑定");
                return httpResult.fail("500").message("群暂未绑定");
            }
            
            if(wechatGroup.getCourse() == null) {
                logger.error("bind user course faild with message : [{}]", "群暂无课程信息");
                return httpResult.fail("500").message("群暂无课程信息");
            }
        
            userCourseService.create(user, wechatGroup.getCourse(), wechatGroup.getOpengid());
            return httpResult.success().message("绑定成功");
        } catch (Exception e) {
            logger.error("bind user course faild with message : [{}]", e);
            return httpResult.fail("500").message("绑定群失败");
        }
    }
    
}
